package ekahau.ue.registration.client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import org.eclipse.swt.SWT; 
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;

import ekahau.ue.registration.RegisteredClientResponse;
import ekahau.ue.registration.RegistrationClientRequest;
import ekahau.ue.registration.RegistrationClientRequest.PREFERENCE_TYPE;

public class Client{

	private static int PORT = 9004;
	private Socket socket;
    private ObjectOutputStream output;
    private ObjectInputStream input;
    private BroadCastListener bListene ;
    //public static String MAC_ADDRESS = "00:18:8E:20:41:37";
    public static String MAC_ADDRESS = "00:18:8E:20:41:60";
    private Combo combo;
    private List list;
    private Label zoneStatus ;
    private Display display;
    PREFERENCE_TYPE selectedPreference = PREFERENCE_TYPE.ALL;
    String slist[] = new String[0];
	String zoneName = null;
	public Client(String sAddress, int port) {
		 
		// Setup networking
		
        try {
        	socket = new Socket(sAddress, port);
			output = new ObjectOutputStream(socket.getOutputStream());
			RegistrationClientRequest req= new RegistrationClientRequest(selectedPreference,MAC_ADDRESS);
	        output.writeObject(req);
	        output.flush();
	        
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}catch (Exception e) {
			e.printStackTrace();
		}
        
	}
	
	public void init(){
		
		//for (int i = 0; i < 1; i++) {
    	  
    	   final String id = "Daniel" ;
    	   
    	   Shell shell = new Shell(display = new Display());
           shell.setLayout(new FillLayout());
    	   shell.setSize (300, 300);
    	   shell.setText(id);
    	   final Composite canvas = new Composite(shell, SWT.FILL);
    	   GridLayout layout = new GridLayout();
    	   layout.verticalSpacing = 2;
    	   canvas.setLayout(layout);
    	   zoneStatus = new Label(canvas,SWT.CENTER);
    	   zoneStatus.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL ));
    	   zoneStatus.setText("Zone:=");
    	   combo = new Combo(canvas, SWT.NONE);
    	   combo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL ));
    	   for(int i = 0 ; i < RegistrationClientRequest.preferenceString.length ; i++){
    		   combo.add(RegistrationClientRequest.preferenceString[i]); 
    	   }
    	   
    	   combo.addListener(SWT.Selection, new Listener() {
			
			@Override
			public void handleEvent(Event event) {
				if(combo.getSelectionIndex() == 0)
					selectionChanged(RegistrationClientRequest.PREFERENCE_TYPE.INDIAN);
				else if(combo.getSelectionIndex() == 1)
					selectionChanged(RegistrationClientRequest.PREFERENCE_TYPE.THAI);
				else if(combo.getSelectionIndex() == 2)
					selectionChanged(RegistrationClientRequest.PREFERENCE_TYPE.JAPNIES);
				else if(combo.getSelectionIndex() == 3)
					selectionChanged(RegistrationClientRequest.PREFERENCE_TYPE.CONTINENTEL);
				else if(combo.getSelectionIndex() == 4)
					selectionChanged(RegistrationClientRequest.PREFERENCE_TYPE.ITALIAN);
				else if(combo.getSelectionIndex() == 5)
					selectionChanged(RegistrationClientRequest.PREFERENCE_TYPE.ALL);
				
			}
		});
    	   
    	   list = new List(canvas, SWT.BORDER_SOLID);
    	   list.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));
    	   
    	   canvas.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
           
           //shell.pack();
           shell.open();
           shell.setMaximized(false);
           
           Thread thread = new Thread(new BroadCastListener());
           thread.start();
           combo.select(5);			
           while (!shell.isDisposed ()) {
       		if (!display.readAndDispatch ()) 
       			display.sleep ();
       		}
           
		//}
		
		
	}
	
	public void selectionChanged(RegistrationClientRequest.PREFERENCE_TYPE type){
		 
		selectedPreference = type;
			
		RegistrationClientRequest req= new RegistrationClientRequest(selectedPreference,MAC_ADDRESS);
	    try {
			output.writeObject(req);
			output.flush();
		} catch (IOException e) {
			list.setItems(new String[]{"Server is not Responding"});
			e.printStackTrace();
		}catch (Exception e) {
			list.setItems(new String[]{"Server is not Responding"});
			e.printStackTrace();
		}
	    
	}
	/**
     * The appplication main method, which just listens on a port and
     * spawns handler threads.
     */
    public static void main(String[] args) throws Exception {

		 Client client = new Client("localhost",PORT);
		 client.init();
    		
    }
    
    
    private class BroadCastListener implements Runnable{
        
    	private boolean listen = true;
    	
    	public BroadCastListener(){
    		
    	}
    	@Override
		public void run() {
    		
    	   byte[] buffer = new byte[1000];//(int)instrumentation.getObjectSize(new PlayerPosition(0,0,"t"))];
    	   try {
    		   input = new ObjectInputStream(socket.getInputStream());
			   while(listen){
			   	Object obj = (Object)input.readObject();
					if(obj instanceof RegisteredClientResponse){
						RegisteredClientResponse rResponse = (RegisteredClientResponse)obj;
						try{
							//display.asyncExec(new MyRunnable(rResponse.getInfo(), rResponse.getZoneName()));
							slist = rResponse.getInfo();
							zoneName = rResponse.getZoneName();
							display.asyncExec(new Runnable() {
								
								@Override
								public void run() {
									if(slist == null)
						            	return;
									list.removeAll();
									list.setItems(slist);
									zoneStatus.setText("ZoneName:= " + zoneName);
								}
							});
						}catch(Exception e){
							e.printStackTrace();
						}
					}
				}
				
    	   }catch (IOException e) { 
    		   e.printStackTrace();
				System.err.println(e); 
			}catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
    	
    }
    
    class MyRunnable implements Runnable{
		
		String slist[] = new String[0];
		String zoneName = null;
		public MyRunnable(String lis[], String zoneN){
			slist = lis;
			zoneName = zoneN ;
		}
		@Override
		public void run() {
            if(slist == null)
            	return;
			list.removeAll();
			list.setItems(slist);
			zoneStatus.setText("ZoneName:= " + zoneName);
			
			// TODO Auto-generated method stub
			
		}
	};
}
